<template>
	<view class="content">
		<view class="ithui-content mt10">
			<view class="upload">
				<text class="upload-tip">请拍摄并上传你的有效行驶证照片</text>
				<view class="upload-item">
					<u-upload @afterRead="afterRead($event,'zm')" :fileList="uploadList['zm']"
						@delete="deletePic($event,'zm')" name="uploadA" multiple :maxCount="1" width="160" height="100">
						<image src="@/pages/users/static/images/xingshizheng-zm.png" style="width: 160px;height: 100px;">
						</image>
					</u-upload>
					<text class="title">行驶证主页</text>
				</view>
				<view class="upload-item">
					<u-upload @afterRead="afterRead($event,'fm')" :fileList="uploadList['fm']"
						@delete="deletePic($event,'fm')" name="uploadB" multiple :maxCount="1" width="160" height="100">
						<image src="../../static/images/xingshizheng-fm.png" style="width: 160px;height: 100px;">
						</image>
					</u-upload>
					<text class="title">行驶证副页</text>
				</view>
			</view>
			<view>
			</view>
			<view class="confirm">
				<view class="mt-20 b-line tips">请确认行驶证信息：</view>
				<view style="margin-top: 100rpx;" v-if="loading"><u-loading-icon :vertical="true"
						text="识别中"></u-loading-icon></view>
				<view v-else>
					<view class="confirm-item">
						<view class="key">行驶证号</view>
						<text class="val"> {{data.codeNumber||'未上传'}}</text>
					</view>
					<view class="confirm-item">
						<view class="key">车牌号</view>
						<text class="val"> {{data.number||'未上传'}}</text>
						<!-- <view class="xm-box" :class="showKeybord ? 'show':''" @tap="showKeybord = true">
							<view class="xm-input" :class="data.name.length === index ? 'cur':''"
								v-for="(item, index) in 8" :key="index">
								{{ data.name.charAt(index) }}
							</view>
						</view> -->
					</view>
					<view class="confirm-item">
						<view class="key">发动机号码</view>
						<text class="val"> {{data.engineNo||'未上传'}}</text>
						<!-- <view class="val">
							<u-input v-model="data.engineNo" border="none" maxlength="17" placeholder="请输入"
								input-align="right"></u-input>
						</view> -->
					</view>
					<view class="mt-20 confirm-item">
						<view class="key">车辆识别代号</view>
						<text class="val"> {{data.vin||'未上传'}}</text>
						<!-- <view class="val"><u-input v-model="data.vin" maxlength="17" border="none" placeholder="请输入"
								input-align="right"></u-input></view> -->
					</view>
					<view class="mt-20 confirm-item">
						<view class="key">车辆类型</view>
						<text class="val"> {{data.vehicleType||'未上传'}}</text>
					</view>
					<view class="mt-20 confirm-item">
						<view class="key">注册日期</view>
						<text class="val"> {{data.registerDate||'未上传'}}</text>
						<!-- <text class="val" @click="showPickerHandler('registerDate')">
							<text v-if="!data.registerDate" style="font-size: 14px;color: #909399;">请选择</text>
							<text v-else> {{data.registerDate}}</text>
						</text> -->
					</view>
					<view class="mt-20 confirm-item">
						<view class="key">发证日期</view>
						<text class="val"> {{data.issueDate||'未上传'}}</text>
						<!-- <text class="val" @click="showPickerHandler('issueDate')">
							<text v-if="!data.issueDate" style="font-size: 14px;color: #909399;"> 请选择 </text>
							<text v-else> {{data.issueDate}} </text>
						</text> -->
					</view>
					<!-- <view class="confirm-item">
						<view class="key">车辆用途</view>
						<view class="val">
								<text class="val" @click="pickerShow2 = true"><text v-if="!data.use"
										style="font-size: 14px;color: #909399;"> 请选择 </text>
									<text v-else> {{data.use}} </text></text>
						</view>
					</view> -->
					<view class="mt-20 confirm-item">
						<view class="key">可购燃油类型</view>
						<!-- <text class="val"> {{data.OilType }}</text> -->
						<text class="val" @click="pickerShow = true"><text v-if="!data.OilType "
								style="font-size: 14px;color: #909399;"> 请选择 </text>
							<text v-else> {{data.OilType }} </text></text>
				</view>
				<view class="pb-safe ">

				</view>
				<view class="submit ">
					<u-button @click="$u.throttle(nextStep(1), 500)" shape="circle" type="primary" text="提交"></u-button>
				</view>
			</view>
		</view>

	</view>
	</view>

	<!-- 自定义键盘 -->
	<!-- 	<xm-keyboard v-model="showKeybord" maxAutoClose :show="showKeybord" :mask="true" @change="changeValue"
		:maxLength="8" :defaultValue="data.name" :mode="mode" @close="e => showKeybord = e"></xm-keyboard> -->
	<!-- 可购燃油类型 选择 -->
	<u-picker :show="pickerShow" :columns="columns" @confirm="pickerConfirm" @cancel="pickerShow = false"
		@close="pickerShow= false" closeOnClickOverlay></u-picker>
	<!-- 使用用途 选择 -->
	<!-- <u-picker :show="pickerShow2" :columns="columns2" @confirm="pickerConfirm2" @cancel="pickerShow2 = false"
			@close="pickerShow2= false" closeOnClickOverlay></u-picker> -->
	<!-- 日期 -->
	<!-- 	<u-datetime-picker :show="datePickerData.show" mode="date" format="YYYY-MM-DD" v-model="DateNow"
		@confirm="datePickerConfirm" @cancel="datePickerData.show = false" @close="datePickerData.show = false"
		closeOnClickOverlay></u-datetime-picker> -->
</template>

<script setup>
	import {
		ref,
		computed,
		reactive,
		defineProps,
		watch
	} from "vue"
	import API from "@/api/index.js"
	import dayjs from 'dayjs'
	import {
		HTTP_REQUEST_URL,HTTP_PIC_URL
	} from "@/config/app.js"
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';

	onLoad((option) => {
		console.log("addCar", option.addCar);
		uni.setNavigationBarTitle({
			title: "添加车辆"
		})
		if (option.addCar) {
			// 从车辆管理页面跳转过来
			addCar.value = true
		} else {
			addCar.value = false
			// 如果有驾驶证信息 则回显
			if (uni.getStorageSync('driversAuth')) {
				data = Object.assign(userInfo, uni.getStorageSync('driversAuth'))
			}
		}

	})
	const addCar = ref(false)
	const emits = defineEmits('next')
	// 提交数据
	let  data = reactive({
		frontImage: '',
		backImage: '',
		zm: '../../static/images/xingshizheng-zm.png',
		fm: '../../static/images/xingshizheng-fm.png',
		number: '',
		engineNo: '',
		vin: '',
		vehicleType: '',
		registerDate: '',
		issueDate: '',
		codeNumber: '',
		OilType: ''
	})
	let dataZm = reactive({})
	let dataFm = reactive({})
	// 自定义键盘
	const showKeybord = ref(false)
	// 键盘模式
	const mode = computed(() => {
		// let length = data.number;
		// if (length == 0) return 0;
		// return 1
	})
	// 键盘值改变
	const changeValue = ({
		text
	}) => {
		data.number = text;
	}

	const loading = ref(false)

	/* 车辆类型选择器 */
	const pickerShow = ref(false)
	/* 使用用途选择器 */
	const pickerShow2 = ref(false)
	const columns = reactive([
		['汽油', '柴油']
	]);
	const columns2 = reactive([
		['中国2', '美国2', '日本2']
	]);

	const pickerConfirm = ({
		value
	}) => {
		data.OilType  = value[0]
		pickerShow.value = false
	}
	const pickerConfirm2 = ({
		value
	}) => {
		data.use = value[0]
		pickerShow2 = false
	}


	/* date选择器 */
	const datePickerData = ref({
		show: false,
		type: 'registerDate'
	})
	const DateNow = ref(Date.now())


	// 打开选择器
	const showPickerHandler = (type) => {
		datePickerData.show = true;
		datePickerData.type = type
	}

	const datePickerConfirm = ({
		value
	}) => {
		data[datePickerData.type] = dayjs(value).format('YYYY-MM-DD');
		datePickerData.show = false;
		// console.log(data)
	}
	// 图片列表
	const uploadList = reactive([])

	// 删除图片
	const deletePic = (event, type) => {
		// this.uploadList[type].splice(event.index, 1);
		delete uploadList[type]
		if(type=='zm'){
			for(let key in dataZm){
				console.log("dataZm",data[key]);
				delete data[key]
			}
		}else if (type =='fm'){
			for(let key in dataFm){
				console.log("dataFm",data[key]);
				delete data[key]
			}
		}
	}


	// 选择图片
	const afterRead = async (event, type) => {
		// this.loading = true
		console.log("afterRead step222 选择图片", event, type);
		// loading = true
		uploadList[type] = [{
			...event.file[0],
			status: 'uploading',
			message: '上传中'
		}]
		await uni.uploadFile({
			url: HTTP_REQUEST_URL + '/api/Recognize/UploadDriver/' + uni.getStorageSync('userInfo').id +
				'/3', // 仅为示例，非真实的接口地址
			filePath: uploadList[type][0].url,
			name: 'file',
			formData: {
				file: uploadList[type][0]
			},
			success: (uploadFileRes) => {
				const fileData = JSON.parse(uploadFileRes.data);
				console.log("uploadFileRes", fileData);
				if (fileData.data == null || fileData.data == '') {
					delete uploadList[type]
					uni.showToast({
						title: '上传驾驶证有误,请重新上传',
						icon: 'none'
					})
					return
				}
				const cleanObj = {};
				for (const key in fileData.data) {
				  if (fileData.data[key]) {
				    cleanObj[key] = fileData.data[key];
				  }
				}
				console.log("cleanObj",cleanObj);
				if (type == 'zm') {
					dataZm = cleanObj
					dataZm.frontImage =  HTTP_REQUEST_URL+'/' + fileData.msg
				}
				if (type == 'fm') {
					dataFm = cleanObj
					dataFm.backImage =  HTTP_REQUEST_URL+'/' + fileData.msg
				}
				data = {
					...dataZm,...dataFm
				}
				// for (let key in fileData.data) {
				// 	// console.log(data[key], key, fileData.data[key]);
				// 	data[key] = fileData.data[key] ? fileData.data[key] : data[key]
				// }
				uploadList[type] = [{
					...uploadList[type][0],
					status: 'success',
					message: ''
				}]
				console.log("driversAuth", dataZm,dataFm);
			}
		})

	}

	/* 提交 */
	const nextStep = async () => {
		if (addCar.value) {
			// 从车辆管理过来：只提交当前页面
			if (!data.frontImage || !data.backImage) {
				uni.showToast({
					title: '请先正确上传身份证！',
					icon: 'none'
				})
				return
			}
			if (!data.codeNumber || !data.vehicleType ) {
				uni.showToast({
					title: '身份证上传有误！',
					icon: 'none'
				})
				return
			}
			if (data.OilType == undefined ||data.OilType == '') {
				uni.showToast({
					title: '请选择可够燃油类型！',
					icon: 'none'
				})
				return
			}
			let id = await API.uuid()
			let userInfo = uni.getStorageSync('userInfo')
			console.log(userInfo,data);
			let res = await API.saveVehicleInfo({
				// 后台修改信息 必要字段------------------
				Id:id.data,
				RegisterUserId :userInfo.id,
				RegisterDeptId :userInfo.deptId,
				RegisteTime :userInfo.registeTime,
				EditTime : +new Date(),
				editUserId:userInfo.id,
				//----------------------------
				BackImage: data.backImage,
				UserId :userInfo.id,
				OilType: data.OilType,
				License: data.codeNumber,
				EngineNo: data.engineNo,
				FrontImage: data.frontImage,
				LicenseDate: data.issueDate,
				CarPlate: data.number,
				RegCheDate: data.registerDate,
				Vtype: data.vehicleType,
				IdNumber: data.vin
			})
			console.log("提交 driversAuth",  res);
			uni.showToast({
				title:res.msg,icon:'none'
			})
			// uni.hideLoading()
			// 触发全局事件
			uni.$emit('isEdit', true)
			setTimeout(()=>{
				uni.navigateBack()
				// uni.redirectTo({
				// 	url:'/pages/users/user_car_list/index'
				// })
			},1500)
			// uni.setStorageSync('driversAuth', cleanObj);
		} else {
			// 从个人身份认证页面跳转过来
		}

		// 下一步
		// emits('next', 2)
	}
</script>



<style lang="scss" scoped>
	.ithui {


		&-content {
			.upload {
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
				padding: 0 25rpx;
				background-color: #fff;

				&-tip {
					padding: 10rpx 0;
					font-size: 14px;
					color: #999;
				}

				&-item {
					width: 310rpx;
					padding: 20rpx;
					text-align: center;

					.title {
						color: #999;
						font-size: 28rpx;
						line-height: 28rpx;
					}
				}
			}

			.confirm {
				.tips {
					color: #999;
					font-weight: normal;
					font-size: 32rpx;
					padding: 30rpx;
					background-color: #fff;
				}

				&-item {
					display: -webkit-box;
					display: -webkit-flex;
					display: flex;
					-webkit-box-align: center;
					-webkit-align-items: center;
					align-items: center;
					padding: 25rpx 30rpx;
					position: relative;
					background-color: #fff;

					.key {
						-webkit-box-flex: 1;
						-webkit-flex: 1;
						flex: 1;
						min-width: 0;
						font-size: 28rpx;
						color: #333;
						// font-weight: bold;
					}

					.val {}
				}

				.b-line {
					position: relative;

					&:after {
						content: '';
						position: absolute;
						z-index: 2;
						bottom: 0;
						left: 0;
						width: 100%;
						height: 2rpx;
						border-bottom: 2rpx solid #e2e2e2;
						transform: scaleY(0.5);
						transform-origin: 0 100%;
						-webkit-transform: scaleY(0.5);
						-webkit-transform-origin: 0 100%;
					}
				}
			}

			.pb-safe {
				padding-bottom: env(safe-area-inset-bottom);
				height: 200rpx;
			}

			.submit {
				position: fixed;
				width: 90%;
				padding: 0 5%;
				bottom: 20rpx;
				// padding: 20px;
			}
		}
	}

	.xm-box {
		display: flex;
		justify-content: space-between;

		&.show {
			.cur {
				border-color: #007AFF;

				@keyframes blink {
					0% {
						opacity: 0;
					}

					50% {
						opacity: 1;
					}

					100% {
						opacity: 0;
					}
				}

				&::after {
					color: #007AFF;
					content: '|';
					animation: blink 1s infinite;
				}
			}
		}

		.xm-input {
			margin-right: 10rpx;
			border: 1px solid #CCC;
			border-radius: 2px;
			width: 50rpx;
			height: 40px;
			display: flex;
			justify-content: center;
			align-items: center;

			&:last-child {
				margin-right: 0;
				border-style: dashed;
			}
		}

		&.cjh .xm-input {
			margin-right: 3px;
			border: none;
			border-bottom: 1px solid #CCC;
			border-radius: 0;
		}
	}
</style>